// src/plugins/websocket.js
export default {
    install(Vue, options) {
        let socket = null;

        Vue.prototype.$ws = {
            connect(url) {
                if (socket) {
                    socket.close();
                }

                socket = new WebSocket(url);

                socket.onopen = () => {
                    console.log('WebSocket 连接已建立');
                };

                socket.onmessage = (event) => {
                    const message = JSON.parse(event.data);
                    console.log('WebSocket 收到消息:', message);

                    // 处理接收到的消息
                    if (message.type === 'authenticated') {
                        console.log('用户已验证');
                    } else if (message.type === 'authentication_failed') {
                        console.error('用户验证失败');
                        socket.close();
                    }
                };

                socket.onclose = () => {
                    console.log('WebSocket 连接已关闭');
                };

                socket.onerror = (error) => {
                    console.error('WebSocket 错误:', error);
                };
            },
            send(data) {
                if (socket && socket.readyState === WebSocket.OPEN) {
                    socket.send(JSON.stringify(data));
                } else {
                    console.error('WebSocket 未打开。当前状态:', socket.readyState);
                }
            },
            close() {
                if (socket) {
                    socket.close();
                }
            }
        };
    }
};
